package com.base.core.common.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {
    public static String md5(String input) {
        if (input == null || input.length() == 0) {
            return null;
        }

        try {
            // 创建MessageDigest实例
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 计算MD5哈希值
            byte[] digest = md.digest(input.getBytes(StandardCharsets.UTF_8));

            // 将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : digest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }

            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 algorithm not found", e);
        }
    }

    /**
     * MD5加密（32位大写）
     * @param input 待加密字符串
     * @return 加密后的32位大写MD5字符串
     */
    public static String md5UpperCase(String input) {
        String md5 = md5(input);
        return md5 != null ? md5.toUpperCase() : null;
    }
}
